package com.block.account.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.block.account.model.dto.EntryAccountDTO;
import com.block.account.service.IAccountActionHandleService;
import com.block.account.service.IAccountInfoHisService;
import com.block.common.service.LogFactory;
import com.block.common.util.BigDecimalUtil;
import com.block.db.entity.AccountInfo;
import com.block.db.mapper.AccountInfoMapper;
import com.block.account.service.IAccountInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;

/**
 * <p>
 * 总账号信息表 服务实现类
 * </p>
 *
 * @author 
 * @since 2023-02-02
 */
@Service
public class AccountInfoServiceImpl extends ServiceImpl<AccountInfoMapper, AccountInfo> implements IAccountInfoService, IAccountActionHandleService {

    private static Logger log = LogFactory.getCommLog();

    @Autowired
    IAccountInfoHisService accountInfoHisService;

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public boolean entryAccountInfo(EntryAccountDTO entryAccountDTO) {

        AccountInfo accountInfo = this.baseMapper.getEntityByAccountIdLock(entryAccountDTO.getItemAccountId());
        if (ObjectUtil.isEmpty(accountInfo)){
            return false;
        }

        BigDecimal avaliableAmount = BigDecimalUtil.add(entryAccountDTO.getChangeAmount(), accountInfo.getAvailableAmount());
        BigDecimal totalAmount = BigDecimalUtil.add(entryAccountDTO.getChangeAmount(), accountInfo.getTotalAmount());

        AccountInfo updateEntity = new AccountInfo();
        updateEntity.setId(accountInfo.getId());
        updateEntity.setAvailableAmount(avaliableAmount);
        updateEntity.setTotalAmount(totalAmount);
        boolean updateRes = this.updateById(updateEntity);
        log.info("【总账户入账】更新总账户完成【updateRes】{}【entryAccountDTO】{}", updateRes, JSON.toJSONString(entryAccountDTO));
        if (!updateRes){
            return false;
        }

        entryAccountDTO.setOriginAmount(accountInfo.getTotalAmount());
        entryAccountDTO.setCurrentAmount(totalAmount);
        boolean hisRes = accountInfoHisService.saveAccountHisInfo(accountInfo, entryAccountDTO);
        log.info("【总账户入账】新增总账户历史【hisRes】{}【entryAccountDTO】{}", hisRes, JSON.toJSONString(entryAccountDTO));
        if (!hisRes){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return hisRes;
    }

}
